<template>
  <el-dialog
    v-model="visible"
    title="开启TOTP"
    width="400px"
    @close="resetForm"
  >
    <el-image :src="qrUrl" style="width: 100%" />
    <el-form ref="userFormRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="otpCode" prop="otpCode">
        <el-input v-model="form.otpCode" placeholder="请输入otpCode" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button :loading="submitLoading" type="success" @click="submitForm">
        确认
      </el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { enableTotp } from "@/api/totpApi";
import { message } from "@/utils/message";

interface UserForm {
  setupId: string;
  otpCode: string;
}
const visible = ref(false);
const qrUrl = ref("");
const form = reactive<UserForm>({
  setupId: "",
  otpCode: ""
});

const emits = defineEmits(["refresh"]);

const rules: FormRules = {
  otpCode: [{ required: true, message: "请输入otpCode", trigger: "blur" }]
};

const userFormRef = ref<FormInstance>();
const submitLoading = ref(false);
const submitForm = () => {
  userFormRef.value?.validate(async valid => {
    if (valid) {
      try {
        submitLoading.value = true;
        await enableTotp(form);
        message("更新成功", { type: "success" });
        visible.value = false;
        emits("refresh");
      } catch (error) {
        console.error(error);
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

const resetForm = () => {
  userFormRef.value?.resetFields();
  userFormRef.value?.clearValidate();
};
const open = ({ url, setupId }) => {
  form.setupId = setupId;
  qrUrl.value = url;
  visible.value = true;
};

defineExpose({ open });
</script>
